import {Component, OnInit} from '@angular/core';
import {NzMessageService, NzModalSubject} from "ng-zorro-antd";
import {ResourceService} from "../resource.service";

class Resource {
    id;
    pid;
    name;
    icon;
    url;
    method;
    sort;
    ismenu;
    enable;
    remark;
}

@Component({
    selector: 'app-resource-edit',
    templateUrl: './resource-edit.component.html',
    styleUrls: ['./resource-edit.component.scss']
})
export class ResourceEditComponent implements OnInit {

    i;

    _item: Resource = new Resource();
    _options = null;
    _loaded = false;
    _value: any[] = [];

    _changeValue(value) {
        this._item.pid = this._value[this._value.length - 1];
    }

    _addIsLeafField(list) {
        list.forEach((val, idx, array) => {
            if (val.children) {
                this._addIsLeafField(val.children);
            } else {
                val.isLeaf = true;
            }
        });
    }

    _setValue(list, pid) {
        if (pid === 0) {
            return;
        }
        list.forEach((val, idx, array) => {
            if (pid === val.id) {
                this._value.unshift(val);
                this._setValue(this._options, val.pid);
            } else {
                if (val.children) {
                    this._setValue(val.children, pid);
                }
            }
        });
    }

    _setParent(cur) {
        if (cur.parent) {
            this._value.unshift(cur.parent);
            this._setParent(cur.parent);
        }
    }

    save() {
        this.resourceService.save(this._item).subscribe(() => {
            this.nzMessage.success('保存成功');
            this.subject.next(true);
            this.close();
        });
    }

    close() {
        this.subject.destroy();
    }

    constructor(private subject: NzModalSubject,
                private nzMessage: NzMessageService,
                private resourceService: ResourceService) {
    }

    ngOnInit() {
        this._setParent(this.i);
        this._item.id = this.i.id;
        if (this._item.id > 0) {
            this._item.pid = this.i.pid;
            this._item.name = this.i.name;
            this._item.icon = this.i.icon;
            this._item.url = this.i.url;
            this._item.method = this.i.method;
            this._item.sort = this.i.sort;
            this._item.ismenu = this.i.ismenu;
            this._item.enable = this.i.enable;
            this._item.remark = this.i.remark;
        } else {
            this._item.pid = 0;
            this._item.ismenu = false;
            this._item.enable = false;
        }
        this.resourceService.getMenuTree().subscribe(data => {
            this._addIsLeafField(data);
            this._options = data;
            // this._setValue(this._options, this.i.pid);
            this._loaded = true;
        });
    }

}
